<template>
	<view class="page-box">
		<view style="width: 100vw;text-align: center;font-size: 32rpx;font-weight: 900;color: #fff;line-height: 80rpx;">旧机质检</view>
		
		<view class="sel-box">
			<view class="h2-font">基本信息</view>
			<view style="margin: 20rpx;">
				<u--form>
					<u-form-item label="机型" @click="handleModel">
						<u-input placeholder="请选择机型" v-model="form.modelName" disabled border="none" disabledColor="#ffffff"></u-input>
						<u-icon slot="right" name="arrow-right"></u-icon>
					</u-form-item>
					<u-form-item label="IEMI">
						<u-input placeholder="请输入IEMI" border="none" v-model="form.iemi"></u-input>
					</u-form-item>
				</u--form>
			</view>
		</view>
		
		<view class="sel-box" v-if="testArr && testArr.length > 0">
			<view class="h2-font">验机报告</view>
			<u-collapse :border="false" :value="collapseVal" ref="coll_dom">
			    <u-collapse-item
			      :title="item.name"
				  :value="item.selIndex != null ? item.children[item.selIndex].name : ''"
			      :name="item.id"
				  v-for="(item,key) in testArr"
			    >
			      <view>
					  <view 
						:class="item.selIndex === index ? 'sel-item-box':'item-box'" 
						v-for="(c, index) in item.children"
						@click="itemChange(key, index)"
					>{{c.name}}</view>
				  </view>
			    </u-collapse-item>
			  </u-collapse>
		</view>
		
		<view class="sel-box">
			<view class="h2-font">机器照片</view>
			<view style="margin: 30rpx;">
				<u-upload
					:fileList="fileList"
					@afterRead="afterRead"
					name="1"
					multiple
					:sizeType="['compressed']"
					:maxCount="9"
					@delete="handleDeleteImage"
				></u-upload>
			</view>
		</view>
		
		<view class="sel-box">
			<view class="h2-font">备注（选填）</view>
			<view style="margin: 30rpx;">
				<u--textarea v-model="form.remark" placeholder="请输入内容" count></u--textarea>
			</view>
		</view>
		
		<view style="margin: 30rpx;">
			<u-button type="success" text="发起询价" :disabled="btnLoading" @click="submitForm"></u-button>
		</view>
		
		<view style="height: 100rpx;"></view>
		
		
		<u-popup :show="modelShow" mode="bottom"  @close="modelClose">
			<view>
				<m-selection @change="mSelectionChange"></m-selection>
			</view>
		</u-popup>
	</view>
</template>

<script>
	import mSelection from "@/pages/store/model/selection.vue"
	import $path from "@/utils/ServerPath.js"
	export default {
		components: {mSelection},
		data() {
			return {
				btnLoading: false,
				//文件
				fileList: [],
				//提交表单
				form: {
					modelId: null,
					modelName: null,
					iemi: null,
					remark: '',
				},
				//机型弹出层开关
				modelShow:false,
				//打开的折叠
				collapseVal: [],
				//验机选项
				testArr: [],
			}
		},
		methods: {
			handleDeleteImage(e) {
				this.fileList.splice(e.index, 1)
			},
			/* 提交订单 */
			submitForm() {
				if(!this.form.modelId) {
					uni.showToast({
						title: "请选择机型",
						icon: "error"
					})
					return
				}
				if(!this.form.iemi) {
					uni.showToast({
						title:"请输入IEMI",
						icon: "error"
					})
					return
				}
				if(!this.fileList || this.fileList.length === 0) {
					uni.showToast({
						title: "请上传图片",
						icon: 'error'
					})
					return
				}
				const fileIds = [];
				this.fileList.forEach(it => {
					fileIds.push(it.fileId);
				})
				const verifyModelIds = [];
				this.testArr.forEach(it => {
					if(it.selIndex != null) {
						verifyModelIds.push(it.children[it.selIndex].id)
					}
				})
				if(verifyModelIds.length === 0) {
					uni.showToast({
						title:"请选择验机报告",
						icon: "error"
					})
				}
				this.form.fileIds = fileIds.toString();
				this.form.verifyModelIds = verifyModelIds.toString();
				
				this.$request("/appShopApi/order/insertInquiryOrder", 'post', this.form).then(res => {
					uni.$emit("InquiryOrderFlush");
					uni.showToast({
						title: '发布成功！',
						icon: "success",
						success: () => {
							uni.navigateBack({delta:1});
						}
					})
				})
			},
			//选择机型
			mSelectionChange(e) {
				this.form.modelId = e.id;
				this.form.modelName = e.name;
				this.modelShow = false;
				const params = {
					modelType: e.modelType,
					systemType: e.systemType
				}
				let specsSet = new Set();
				e.specsJson = JSON.parse(e.specsJson);
				e.specsJson.forEach(it => {
					specsSet.add(it[0])
					specsSet.add(it[1])
				})
				this.$request("/appCommon/model/options", 'get', params).then(res => {
					this.testArr = [];
					let specsArr = []; //规格列表
					let testArr = []; //验机列表
					let specsChid = [];
					let testChid = [];
					res.data.forEach(it => {
						if(it.type === 1) {
							if(specsSet.has(it.id)) {
								//规格
								if(it.parentId === 0)
									specsArr.push(it);
								else
									specsChid.push(it);
							}
						}else if(it.type === 2) {
							//验机
							if(it.parentId === 0)
								testArr.push(it);
							else
								testChid.push(it);
						}
					})
					this.setChildren(specsArr, specsChid);
					this.setChildren(testArr, testChid);
					this.testArr.push(...specsArr);
					this.testArr.push(...testArr);
					this.collapseVal = [];
					this.testArr.forEach(it => {
						this.collapseVal.push(it.id);
					})
					this.$nextTick(() => {
						this.$refs.coll_dom.init()
					})
				})
			},
			//设置子集
			setChildren(pArr, cArr) {
				pArr.forEach(pit => {
					pit.children = [];
					pit.selIndex = 0;
					cArr.forEach(cit => {
						if(cit.parentId == pit.id) {
							pit.children.push(cit);
						}
					})
				})
			},
			// 打开机型选择弹出层
			handleModel() {
				this.modelShow = true;
			},
			// 关闭机型选择弹出层
			modelClose() {
				this.modelShow = false;
			},
			// 折叠面板选择后关闭
			itemChange(key, index) {
				this.testArr[key].selIndex = index;
				for(let i = 0; i < this.collapseVal.length; i++) {
					if(this.collapseVal[i] === this.testArr[key].id){
						this.collapseVal.splice(i, 1);
					}
				}
				this.$nextTick(() => {
					this.$refs.coll_dom.init()
				})
				
			},
			// 新增图片
			async afterRead(event) {
				this.btnLoading = true;
				// 当设置 multiple 为 true 时, file 为数组格式，否则为对象格式
				let lists = [].concat(event.file)
				let fileListLen = this[`fileList`].length
				lists.map((item) => {
					this[`fileList`].push({
						...item,
						status: 'uploading',
						message: '上传中'
					})
				})
				for (let i = 0; i < lists.length; i++) {
					const result = await this.uploadFilePromise(lists[i].url)
					let item = this[`fileList`][fileListLen]
					this[`fileList`].splice(fileListLen, 1, Object.assign(item, {
						status: 'success',
						message: '',
						url: result.url,
						fileId: result.fileId
					}))
					fileListLen++
				}
				this.btnLoading = false;
			},
			uploadFilePromise(url) {
				return new Promise((resolve, reject) => {
					let a = uni.uploadFile({
						url: $path.prefix + '/appCommon/upload', // 仅为示例，非真实的接口地址
						filePath: url,
						name: 'file',
						formData: {
							prefix: $path.url
						},
						success: (res) => {
							console.log("文件上传回调信息：", JSON.parse(res.data).url)
							setTimeout(() => {
								resolve(JSON.parse(res.data))
							}, 1000)
						}
					});
				})
			},
		}
	}
</script>

<style scoped lang="scss">
	.page-box {
		background-image: linear-gradient(#19be6b 10%, #f2f8fc 40%);
		height: 100vh;
	}
	.sel-box {
		background-color: #ffffff;
		margin: 20rpx;
		padding: 20rpx;
		border-radius: 20rpx;
	}
	.item-box {
		display: inline-block;
		margin: 10rpx;
		padding: 10rpx 20rpx;
		border-radius: 20rpx;
		border: #19be6b solid 1px;
		color: #19be6b;
	}
	.sel-item-box {
		display: inline-block;
		margin: 10rpx;
		padding: 10rpx 20rpx;
		border-radius: 20rpx;
		background-color: #19be6b;
		color: #FFF;
	}
</style>
